package com.hyl.icon.testdemo;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

public class LogoBrandGenerator {

    public static void main(String[] args) {
        // 示例代码，如果是通过Controller调用，MultipartFile参数会来自前端请求
        MultipartFile backgroundFile = null; // 通过前端上传的背景图
        MultipartFile logoFile = null; // 通过前端上传的 Logo 图
        String brandName = "菠萝甜心橙"; // 品牌名称
        File outputFile = new File("D:\\workspace\\icon\\test\\images\\output_logo.png");

        try {
            // 调用方法生成品牌图
            generateBrandImage(backgroundFile, logoFile, brandName, outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成品牌 Logo 图片
     *
     * @param backgroundFile 背景图片 MultipartFile
     * @param logoFile       Logo 图片 MultipartFile
     * @param brandName      品牌名称
     * @param outputFile     输出文件路径
     */
    public static void generateBrandImage(MultipartFile backgroundFile, MultipartFile logoFile, String brandName, File outputFile) throws IOException {
        try {
            // 读取背景图片
            BufferedImage background = convertMultipartFileToBufferedImage(backgroundFile);
            int width = background.getWidth();
            int height = background.getHeight();

            // 创建新图像
            BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = outputImage.createGraphics();

            // 开启抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 画背景图
            g2d.drawImage(background, 0, 0, null);

            // 计算 Logo 尺寸（占背景高度的 1/4）
            int logoHeight = height / 4;
            int logoWidth = logoHeight;  // 假设 Logo 为正方形

            // 计算 Logo 位置（靠近顶部）
            int logoX = (width - logoWidth) / 2;
            int logoY = height / 20;  // 让 Logo 更靠顶部

            // 读取 Logo 图片并缩放
            BufferedImage logo = convertMultipartFileToBufferedImage(logoFile);
            BufferedImage resizedLogo = resizeImage(logo, logoWidth, logoHeight);
            g2d.drawImage(resizedLogo, logoX, logoY, null);

            // 计算品牌名称区域高度（占背景高度的 1/2）
            int brandHeight = height / 2;
            int numChars = brandName.length();
            int fontSize = brandHeight / numChars;  // 计算字体大小，使整体高度固定

            // 限制最小字体大小，防止过小
            fontSize = Math.max(fontSize, height / 20);

            // 设定字体
            g2d.setFont(new Font("SansSerif", Font.BOLD, fontSize));
            g2d.setColor(Color.BLACK);

            // 计算品牌名和 Logo 之间的间距（增大间距，防止接触）
            int spaceBetween = logoHeight / 4;
            int textStartY = logoY + logoHeight + spaceBetween;
            int textX = (width - fontSize) / 2;

            // 竖排绘制品牌名称
            for (char c : brandName.toCharArray()) {
                g2d.drawString(String.valueOf(c), textX, textStartY);
                textStartY += fontSize;  // 每个字的间距等于字体大小
            }

            // 释放资源
            g2d.dispose();

            // 保存图片
            ImageIO.write(outputImage, "PNG", outputFile);
            System.out.println("品牌 Logo 生成完成：" + outputFile.getAbsolutePath());

        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException("生成品牌 Logo 图片失败", e);
        }
    }

    /**
     * 将 MultipartFile 转换为 BufferedImage
     */
    private static BufferedImage convertMultipartFileToBufferedImage(MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        return ImageIO.read(bais);
    }

    /**
     * 缩放图片
     */
    private static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(originalImage, 0, 0, width, height, null);
        g2d.dispose();
        return resizedImage;
    }
}
